#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <sys/wait.h>

#define MAX 1024
#define ARGC 64
#define SEP " "

int split(char* commandstr,char* argv[])
{
  assert(commandstr);
  assert(argv);
  
  argv[0] = strtok(commandstr,SEP);
  if(argv[0] == NULL) return -1;
  int i = 1;
  while((argv[i++] = strtok(NULL,SEP)));
  return 0;
}

int main()
{
  while(1)
  {
    char commandstr[MAX] = {0};
    char* argv[ARGC] = {NULL};
    printf("[nhy@VM-4-12-centos my--bash]$");
    fflush(stdout);
    char* s = fgets(commandstr,sizeof(commandstr),stdin);

    assert(s);
    (void)s; //防止在release优化时因去掉assert产生的警告

    //abcd\n 把原来\n的位置给换成\0 字符串以\0结尾
    commandstr[strlen(commandstr)-1] = '\0';
    int n = split(commandstr,argv);
    if(n != 0) continue;//命令输入的不对
    //-----------------------------------------------------------------
    //细节说明
    //
    
    //这些让bash自己执行的命令（说人话就是让父进程执行），我们称之为内建命令
    if(strcmp(argv[0],"cd") == 0)
    {
      if(argv[1] != NULL) chdir(argv[1]);
      continue;
    }


    if(strcmp(argv[0],"ls") == 0)
    {
      int pos = 0;
      while(argv[pos]) pos++;
      argv[pos++] = (char*)"--color=auto";
      argv[pos] = NULL;

    }
    //--------------------------------------------------------------------

    pid_t id = fork();
    assert(id >= 0);
    (void)id;

    if(id == 0)
    {
      execvp(argv[0],argv);
    }

    int status = 0;
    waitpid(id,&status,0);
  }
  return 0;
}
